package com.bigluo.util.md5;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class MapUtils {
    private static Logger logger = LoggerFactory.getLogger(MapUtils.class);

    /**
     * 使用 Map按key进行排序
     *
     * @param map
     * @return
     */
    public static String sortStringByKey(Map<String, String> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }
        Map<String,String> sortMap = new TreeMap<String, String>(new Comparator<String>() {
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);
            }
        });
        sortMap.putAll(map);

        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, String> entry : sortMap.entrySet()) {
            sb.append(entry.getKey());
            sb.append("=");
            sb.append(entry.getValue());
            sb.append("&");
        }

        sb.deleteCharAt(sb.lastIndexOf("&"));
        return sb.toString();
    }

    /**
     * 使用 Map按key进行排序
     *
     * @param map
     * @return
     */
    public static String sortStringByLine(Map<String, String> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }
        Map<String, String> sortMap = new TreeMap<String, String>(new Comparator<String>() {
            public int compare(String str1, String str2) {
                return str1.compareTo(str2);
            }
        });
        sortMap.putAll(map);

        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, String> entry : sortMap.entrySet()) {
            sb.append(entry.getValue());
            sb.append("|");
        }
        return sb.toString();
    }

    /**
     * 移除值为空的数据项
     *
     * @param map
     * @return
     */
    public static Map<String, String> removeNull(Map<String, String> map) {

        Map<String, String> resultMap = new HashMap<String, String>();

        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (entry.getValue() != null && !"".equals(entry.getValue())) {
                resultMap.put(entry.getKey(), entry.getValue());
            }
        }
        return resultMap;
    }

    /**
     * @param parms
     * @return
     * @brief 校验是否有空值参数
     */
    public static boolean isBlank(Object... parms) {
        for (int i = 0; i < parms.length; i++) {
            if (parms[i] == null || !StringUtils.hasText(parms[i]+"")) {
                return true;
            }
        }
        return false;
    }

}
